﻿using Wen.Core.Helps;
using WenAntdUI.Services;
using WenAntdUI.Settings;

namespace WenAntdUI.Login
{
    public partial class LoginForm : WenForm
    {
        private IFreeSql fsql;
        private UserService userService;
        private IdentityService identity;
        public LoginForm(IFreeSql fsql, UserService userService, IdentityService identity)
        {
            this.fsql = fsql;
            this.userService = userService;
            this.identity = identity;
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;

            var steebutton = new AntdUI.Button()
            {
                IconSvg = "SettingOutlined",
                Dock = DockStyle.Right,
                Width = 40,
            };
            steebutton.Click += (s, e) => new Settings.SettingsForm().ShowDialog();
            this.TopControls.Add(steebutton);


            input_User.Text = AppSettings.GetString("UserInfo:User") ?? "";
            try
            {
                var configPassword = AppSettings.GetString("UserInfo:Password");
                if (!string.IsNullOrWhiteSpace(configPassword))
                {
                    var pssword = AesRsaHelp.Decrypt(configPassword);
                    input_Password.Text = pssword;
                    checkbox1.Checked = true;
                }
            }
            catch (Exception ex) { }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            var username = input_User.Text;
            var password = input_Password.Text;

            AppSettings.Set("UserInfo:User", username);
            if (checkbox1.Checked)
            {
                AppSettings.Set("UserInfo:Password", AesRsaHelp.Encrypt(password));
            }
            else
            {
                AppSettings.Set("UserInfo:Password", "");
            }


            if (userService.VerifyLogin(username, password))
            {
                DialogResult = DialogResult.OK;
                identity.SetUserInfo(username, password);
                return;
            }
            else
            {
                alert1.Icon = AntdUI.TType.Error;
                alert1.Text = "用户名或者密码错误！";
            }

        }
    }
}
